package com.example.demo.controller;

import com.example.demo.core.Result;
import com.example.demo.pojo.response.QuartzCronTriggerResponse;
import com.example.demo.pojo.response.QuartzJobDetailResponse;
import com.example.demo.service.QuartzSchedulerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 任务调度管理
 *
 * @author Ethan Blake
 * @version 1.0
 * @since 2024/8/27
 */
@Tag(name = "任务调度", description = "任务调度")
@RestController
@RequestMapping("/scheduler")
@RequiredArgsConstructor
public class SchedulerController {

    private final QuartzSchedulerService quartzSchedulerService;


    /**
     * 获取所有JobDetails
     *
     * @return API全局响应对象
     */
    @Operation(summary = "获取所有JobDetails")
    @PostMapping("/jobs")
    @PreAuthorize("hasAuthority('/scheduler/jobs')")
    public Result<List<QuartzJobDetailResponse>> getAllQuartzJobDetail() {
        List<QuartzJobDetailResponse> allJobDetails = quartzSchedulerService.getAllJobDetails();
        return Result.ok(allJobDetails);
    }

    @Operation(summary = "获取所有Cron Trigger(基于Cron的调度器)")
    @PostMapping("/trigger")
    @PreAuthorize("hasAuthority('/scheduler/cronTrigger')")
    public Result<List<QuartzCronTriggerResponse>> getAllCronTrigger() {
        List<QuartzCronTriggerResponse> allJobDetails = quartzSchedulerService.getAllTriggers();
        return Result.ok(allJobDetails);
    }

    /**
     * 修改指定Cron调度器的Cron表达式
     *
     * @param triggerName       要修改的调度器名称
     * @param triggerGroup      要修改的调度器分组
     * @param newCronExpression 新的Cron表达式
     * @return
     */
    @Operation(summary = "修改指定Cron调度器的Cron表达式")
    @PostMapping("/updateCronTrigger/{triggerName}/{triggerGroup}")
    @PreAuthorize("hasAuthority('/scheduler/updateCronTrigger')")
    public Result<Void> updateCronTrigger(@PathVariable String triggerName, @PathVariable String triggerGroup, String newCronExpression) {
        quartzSchedulerService.updateCronTrigger(triggerName, triggerGroup, newCronExpression);
        return Result.ok();
    }

}
